package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TanhuaService {
    @Value("${tanhua.default.recommend.users}")
    private String recommendUser;
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private HuanXinTemplate template;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MessagesService messagesService;

    @DubboReference
    private UserLocationApi userLocationApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    public TodayBest todayBest() {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用API查询
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        //保证能查到一条
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        //查询当前用户的数据
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        //3、将RecommendUser转化为TodayBest对象
        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
        //4、返回
        return todayBest;
    }

    //查询分页推荐好友列表
    public PageResult recommendation(RecommendUserDto dto) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用recommendUserApi分页查询
        PageResult pr = recommendUserApi.queryRecommendUserList(dto.getPage(), dto.getPagesize(), userId);
        //3、获取分页中的（用户推荐表的数据（里面有用户有兴趣的用户和心动值））RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        //4、判断列表是否为空
        if (items == null || items.size() <= 0) {
            return pr;
        }
        //5、提取所有推荐的用户id列表(工具类，类似于循环拿id)
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        //6、构建查询条件，批量查询所有的用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, dto.getAge(), dto.getGender());
        //7、循环推荐的数据列表，构建vo对象
        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo userInfo = map.get(item.getUserId());//根据id查用户
            if (userInfo != null) {
                //获得前端需要的用户数据，放items里的数据
                TodayBest vo = TodayBest.init(userInfo, item);
                list.add(vo);
            }
        }
        pr.setItems(list);
        //8、构造返回值
        return pr;

    }

    //查看佳人信息 传过来的是推荐用户的id
    public TodayBest personalInfo(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        Long id = UserHolder.getUserId();//用户id
        RecommendUser recommendUser = recommendUserApi.findRecommendUser(userId, id);
        //保存访客记录
        Visitors visitors =new Visitors();
        visitors.setDate(System.currentTimeMillis());
        visitors.setUserId(userId);
        visitors.setFrom("首页");
        visitors.setVisitorUserId(id);
        visitors.setVisitDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        visitors.setScore(recommendUser.getScore());
         visitorsApi.save(visitors);
        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
        return todayBest;
    }

    //{"userId":106,
// "huanXinId":"hx106",
// "nickname":"黑马小妹",
// "strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？",
// "reply":"我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"}
    public void replyQuestions(Long userId, String reply) {
        //userId为陌生人的id
        Long id = UserHolder.getUserId();//获得自己的id
        UserInfo userInfo = userInfoApi.findById(id);//获得对方的用户信息
        Map map = new HashMap();
        map.put("userId", id);
        map.put("huanXinId", Constants.HX_USER_PREFIX + id);
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", questionApi.findByTxT(id));
        map.put("reply", reply);
        String jsonString = JSON.toJSONString(map);
        template.sendMsg(Constants.HX_USER_PREFIX + userId, jsonString);
    }

    //探花-推荐用户列表
    public List<TodayBest> queryCardsList() {
        //1、调用推荐API查询数据列表（排除喜欢/不喜欢的用户，数量限制）
        List<RecommendUser> users = recommendUserApi.queryCardsList(UserHolder.getUserId(), 10);
        //2、判断数据是否存在，如果不存在，构造默认数据 1,2,3
        if (CollUtil.isEmpty(users)) {
            users = new ArrayList<>();
            String[] userIdS = recommendUser.split(",");
            for (String userId : userIdS) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setToUserId(UserHolder.getUserId());
                recommendUser.setScore(RandomUtil.randomDouble(60, 90));
                users.add(recommendUser);
            }
        }
        List<Long> ids = CollUtil.getFieldValues(users, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(ids, null, null);
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : users) {
            UserInfo userInfo = userInfoMap.get(user.getUserId());
            if (userInfo != null) {
                TodayBest vo = TodayBest.init(userInfo, user);
                vos.add(vo);
            }
        }
        return vos;
    }

    //右划喜欢
    public void loveUser(Long likeUserId) {
        //调用api保存喜欢数据到mongoDB
        Long userId = UserHolder.getUserId();
        boolean bl = userLikeApi.save(likeUserId,userId);
        if (!bl) {//如果失败
            throw new BusinessException(ErrorResult.error());
        }
        //2、操作redis，写入喜欢的数据，删除不喜欢的数据 (喜欢的集合，不喜欢的集合)
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY+ userId, likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY+ userId, likeUserId.toString());
        //3、判断是否双向喜欢
        Boolean aBoolean = redisTemplate.opsForSet().isMember(Constants.USER_LIKE_KEY + likeUserId, userId.toString());
        if (aBoolean) {//如果都喜欢添加好友
            messagesService.contacts(likeUserId);
        }
    }
  //左滑不喜欢
    public void unLoveUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        boolean bl=  userLikeApi.saveToUnLove(likeUserId,userId);
        if (!bl) {//如果失败
            throw new BusinessException(ErrorResult.error());
        }
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY+userId, likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY+userId, likeUserId.toString());
        messagesService.deleteFriend(userId,likeUserId);
    }
  //搜附近
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //1、调用API查询附近的用户（返回的是附近的人的所有用户id，包含当前用户的id）
               List<Long> userIds=userLocationApi.findByUserInfo(UserHolder.getUserId(),gender,Double.valueOf(distance));
        //2、判断集合是否为空CollUtil.isEmpty
        if(CollUtil.isEmpty(userIds)){
            return new ArrayList<>();
        }
        //3、调用UserInfoApi根据用户id查询用户详情
        UserInfo userInfo=new UserInfo();
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null, gender);
        List<NearUserVo> vos =new ArrayList<>();
        for (Long userId : userIds) {
            //排除当前用户
            if(userId == UserHolder.getUserId()) {
                continue;
            }
            UserInfo info = userInfoMap.get(userId);
            if(info!=null){
                NearUserVo init = NearUserVo.init(info);
                vos.add(init);
            }
        }
return vos;
    }

}
